/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
    let n = nums.length;
    nums.sort((a, b)=> a - b);
    let res = []
    for (let i = 0; i < n - 2; i++) {
        if (nums[i] === nums[i-1]) continue;
        let left = i + 1;
        let right = n - 1;
        while (left < right) {
            let sum = nums[i] + nums[left] + nums[right]
            if (sum === 0) {
                res.push([nums[i], nums[left++], nums[right--]]);
                while (nums[left] === nums[left - 1]) left++;
            } else if (sum < 0) {
                left++;
            } else {
                right--;
            }
        }
    }
    return  res;
};

console.log(threeSum([-1, 0, -1, 1, 2, -4]));